package com.olap.starter.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.olap.starter.core.base.BaseService;
import com.olap.starter.mapper.FormMainMapper;
import com.olap.starter.pojo.*;
import com.olap.starter.util.IdUtil;
import com.olap.starter.util.ObjectUtils;
import com.olap.starter.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author WBG
 * @since 2022-12-21
 */
@Service
@DS("online")
public class FormMainServices extends BaseService<FormMainMapper, FormMain> {

    @Autowired
    @Lazy
    private FormMainColumnServices formMainColumnServices;
    @Autowired
    @Lazy
    private FormDesignerServices formDesignerServices;


    @Autowired
    @Lazy
    private FormMainCreateJsonService formMainCreateJsonService;

    public FormMain saveJson(Map<String, Object> params) {
        FormMain formMain = ObjectUtils.mapToObject((Map) params.get("formMain"), FormMain.class);
        formMain.setDeleted(0);
        int version = 1;
        if (formMain.getUuid() == null) {
            formMain.setUuid(new IdUtil().nextId());
        } else {
            List<FormMain> records = getBaseMapper().selectPage(new Page<>(1, 1), new QueryWrapper<FormMain>().eq("uuid", formMain.getUuid()).orderByDesc("version").select("version")).getRecords();
            if (records.isEmpty()) {
                formMain.setUuid(new IdUtil().nextId());
            } else if ("1".equals(formMain.getDesigner())) {
                updateById(formMain);
            } else {
                update(new UpdateWrapper<FormMain>().set("deleted", 1).eq("uuid", formMain.getUuid()));
                version = records.get(0).getVersion() + 1;
            }
        }
        if (!"1".equals(formMain.getDesigner())) {
            formMain.setDeleted(0);
            formMain.setVersion(version);
            save(formMain);
            List<Map> formMainColumn = (List) params.get("formMainColumns");
            List<FormMainColumn> formMainColumns = ObjectUtils.listMapToListObject(formMainColumn, FormMainColumn.class);
            Iterator<FormMainColumn> iterator = formMainColumns.iterator();
            while (iterator.hasNext()) {
                FormMainColumn mainColumn = iterator.next();
                mainColumn.setParentId(formMain.getId());
                if (StringUtils.isBlank(mainColumn.getLabel()) && StringUtils.isBlank(mainColumn.getField())) {
                    iterator.remove();
                }
            }
            formMainColumnServices.saveBatch(formMainColumns);
        }
        return formMain;
    }

    public void saveList(List<Map<String, Object>> formMainList, TableConfig tableConfig) {
        if (formMainList == null) return;

        for (Map<String, Object> formMainMap : formMainList) {
            FormMain formMain = ObjectUtils.mapToObject((Map<String, Object>) formMainMap.get("formMain"), FormMain.class);
            formMain.setUuid(tableConfig.getUuid());
            formMain.setId(null);
            formMain.setTheme(tableConfig.getTheme());
            formMain.setDeleted(0);
            if(formMain.getDesigner() == null || "NAN".equals(formMain.getDesigner().toUpperCase())){
                continue;
            }
            formMain.setTableName(tableConfig.getMainTable());
            formMain.setTableConfigId(Long.valueOf(tableConfig.getId()));
            save(formMain);
            /*if (!"1".equals(formMain.getDesigner())) {
                List<Map> formMainColumn = (List) formMainMap.get("formMainColumns");
                List<FormMainColumn> formMainColumns = ObjectUtils.listMapToListObject(formMainColumn, FormMainColumn.class);
                if (formMainColumn.size() == 0) {
                    formMainColumns = new ArrayList<>();
                }
                Iterator<FormMainColumn> iterator = formMainColumns.iterator();
                while (iterator.hasNext()) {
                    FormMainColumn mainColumn = iterator.next();
                    mainColumn.setParentId(formMain.getId());
                    if (StringUtils.isBlank(mainColumn.getLabel()) && StringUtils.isBlank(mainColumn.getField())) {
                        iterator.remove();
                    }
                }
                formMainColumnServices.saveBatch(formMainColumns);
            }*/
            if (formMainMap.get("formJson") != null) {
                FormMainCreateJson formJson = ObjectUtils.mapToObject((Map<String, Object>) formMainMap.get("formJson"), FormMainCreateJson.class);
                formJson.setId(formMain.getId());
                formMainCreateJsonService.save(formJson);
            }

        }
    }

    public Map<String, Map<String, Object>> getList(TableConfig tableConfig) {
        Map<String, Map<String, Object>> res = new HashMap<>();
        if (tableConfig != null && tableConfig.getId() != null) {
            List<FormMain> list = list(new LambdaUpdateWrapper<FormMain>().eq(FormMain::getTableConfigId, tableConfig.getId()).eq(FormMain::getUuid,tableConfig.getUuid()));
            for (FormMain formMain : list) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("formMain", formMain);
                /*map.put("formMainColumns", formMainColumnServices.list(Wrappers.lambdaQuery(FormMainColumn.class)
                        .eq(FormMainColumn::getParentId, tableConfig.getId())));*/
                if ("0".equals(formMain.getDesigner())) {
                    FormMainCreateJson createJson = formMainCreateJsonService.getOne(Wrappers.lambdaQuery(FormMainCreateJson.class).eq(FormMainCreateJson::getId, formMain.getId()));
                    map.put("formJson", createJson);
                }else{
                    FormDesigner formDesigner = formDesignerServices.getOne(Wrappers.lambdaQuery(FormDesigner.class).eq(FormDesigner::getId, formMain.getCustomForm()));
                    Map<String,Object> map1 = new HashMap<>();
                    map1.put("customJson",formDesigner.getFormJson());
                    map1.put("id",formDesigner.getId());
                    map.put("formJson",map1 );
                }

                res.put(formMain.getFormType(), map);
            }
        }
        return res;
    }
}
